import axios from 'axios';
import ViewUI from 'view-design';
import Cookies from 'js-cookie';
import store from '../store/index.js'
import {router} from '../router/index';

import { host } from '../config/index.js';

const request = axios.create({
    baseURL: host,
    timeout: 300000
});

// 请求拦截器
request.interceptors.request.use(
    config => {
        const token = Cookies.get('token');
        if(token) {
            config.headers.Authorization = 'Bearer ' + token;
        }
        ViewUI.LoadingBar.start();
        return config;
    }
);

// 响应拦截器
request.interceptors.response.use(
    response => {
        ViewUI.LoadingBar.finish();
        if(response.data.code !== 200) {
            if(response.data.code === 1001) {
                ViewUI.Message.error(response.data.message);
                store.commit('logout');
                router.push({name: 'login'});
                return false;
            }
            return Promise.reject(response.data);
        }
        return response.data.data;
    },
    error => {
        ViewUI.LoadingBar.error();
        if (error.response && error.response.data && error.response.data.code){
            if(error.response.data.code === 1001) {
                ViewUI.Message.error(error.response.data.message);
                store.commit('logout');
                router.push({name: 'login'});
                return false;
            }
            return Promise.reject(error.response.data);
        }
        return Promise.reject(error);
    }
);

export default request;